package com.movie.utils;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Liu Jiaquan
 * @Description
 * @date 2024/7/26 9:26
 */
public class PageUtil {
    public static <T> Page<T> PaginatedResult(List<T> list, Integer current, Integer size) {
        Page<T> page = Page.of(current, size);
        List<T> pageRecords = new ArrayList<>();
        if (list == null || list.size() == 0) {
            page.setRecords(pageRecords);
            page.setTotal(0);
            page.setPages(0);
            return page;
        }
        int totalItems = list.size();
        int totalPages = (int) Math.ceil((double) totalItems / size);
        int startIndex = (current - 1) * size;
        int endIndex = Math.min(startIndex + size, totalItems);
        if (startIndex < totalItems) {
            pageRecords = list.subList(startIndex, endIndex);
        } else {
            pageRecords = new ArrayList<>(); // 返回空列表
        }
        page.setRecords(pageRecords);
        page.setTotal(list.size());
        page.setPages(totalPages);
        return page;
    }
}
